<template>
  <div class="phone-register">
    <van-form @submit="onSubmit" ref="formRef">
      <van-cell-group inset>
        <van-field v-model="formData.phone" type="tel" name="phone" label="手机号" placeholder="请输入手机号"
          :rules="phoneRules" />
        <van-field v-model="formData.sms" center name="sms" label="验证码" placeholder="请输入验证码" :rules="codeRules">
          <template #button>
            <van-button size="small" type="primary" class="code-btn"
              :disabled="!!countdown || !formData.phone || !/^1[3-9]\d{9}$/.test(formData.phone)" @click="sendSms">
              {{ countdown ? `${countdown}s后重新获取` : '获取验证码' }}
            </van-button>
          </template>
        </van-field>
        <van-field v-model="formData.password" :type="showPassword ? 'text' : 'password'" name="password" label="密码"
          placeholder="请输入密码" :rules="passwordRules">
          <template #right-icon>
            <van-icon :name="showPassword ? 'eye-o' : 'closed-eye'" @click="showPassword = !showPassword"
              class="eye-icon" />
          </template>
        </van-field>
        <van-field v-model="formData.confirmPassword" :type="showConfirmPassword ? 'text' : 'password'"
          name="confirmPassword" label="确认密码" placeholder="请再次输入密码" :rules="confirmPasswordRules">
          <template #right-icon>
            <van-icon :name="showConfirmPassword ? 'eye-o' : 'closed-eye'"
              @click="showConfirmPassword = !showConfirmPassword" class="eye-icon" />
          </template>
        </van-field>
      </van-cell-group>

      <div class="form-actions">
        <van-button round block type="primary" native-type="submit" :loading="loading">
          注册
        </van-button>
      </div>
    </van-form>

    <div class="other-actions">
      <div class="links">
        <router-link to="/auth/login">已有账号？去登录</router-link>
      </div>

      <div class="divider">
        <span>其他注册方式</span>
      </div>

      <div class="register-types">
        <van-button round block plain class="type-btn" @click="router.push('/auth/register')">
          用户名注册
        </van-button>
        <van-button round block plain class="type-btn" @click="router.push('/auth/email-register')">
          邮箱注册
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { phoneRules, codeRules, passwordRules, generateConfirmPasswordRules } from '@/utils/validate'

const router = useRouter()
const userStore = useUserStore()
const formRef = ref()

const formData = ref({
  phone: '',
  sms: '',
  password: '',
  confirmPassword: ''
})
const loading = ref(false)
const countdown = ref(0)
const showPassword = ref(false)
const showConfirmPassword = ref(false)

const confirmPasswordRules = computed(() => generateConfirmPasswordRules(formData.value.password))

const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const sendSms = async () => {
  try {
    await formRef.value?.validate('phone')
    await userStore.sendSms(formData.value.phone)
    showToast('验证码已发送')
    startCountdown()
  } catch (error: any) {
    showToast(error?.message || '发送失败')
  }
}

const onSubmit = async (values: any) => {
  try {
    loading.value = true
    // 确保表单验证通过
    await formRef.value?.validate()

    await userStore.phoneRegister({
      phone: values.phone,
      sms: values.sms,
      password: values.password
    })
    showToast('注册成功')
    router.push('/auth/login')
  } catch (error: any) {
    if (error?.errors) {
      // 表单验证错误
      showToast(error.errors[0]?.message || '表单验证失败')
    } else {
      // API 错误
      showToast(error.message || '注册失败')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.phone-register {
  .form-actions {
    margin-top: 32px;
    padding: 0 16px;
  }

  .other-actions {
    padding: 0 16px;
    margin-top: 24px;

    .links {
      text-align: center;
      margin-bottom: 24px;

      a {
        color: var(--van-primary-color);
        text-decoration: none;
        font-size: 14px;
      }
    }

    .divider {
      display: flex;
      align-items: center;
      margin: 24px 0;

      &::before,
      &::after {
        content: '';
        flex: 1;
        height: 1px;
        background: var(--van-border-color);
      }

      span {
        padding: 0 16px;
        color: var(--van-text-color-2);
        font-size: 14px;
      }
    }

    .register-types {
      .type-btn {
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}

:deep(.eye-icon) {
  font-size: 16px;
  color: #666;
  padding: 10px;
  margin-right: -10px;
  cursor: pointer;

  &:active {
    opacity: 0.7;
  }
}

.code-btn {
  height: 32px;
  padding: 0 $spacing-md;
  border-radius: $radius-md;
  font-size: 14px;
  background: $primary-color !important;
  border: none;

  &:active {
    opacity: 0.8;
  }

  &.van-button--disabled {
    background: $border-color !important;
    color: $text-placeholder;
  }
}
</style>
